<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import type { User } from "../../../types/user";
import {
  getUserList,
  updateUser,
  deleteUser as deleteUserApi,
} from "../../../api/users";
import { ElMessageBox, ElMessage } from "element-plus";

// 用户数据
const users = ref<User[]>([]);
const total = ref(0);
const loading = ref(false);

// 分页参数
const pagination = ref({
  skip: 0,
  limit: 10,
});

// 搜索关键词
const searchKeyword = ref("");

// 当前编辑的用户
const editingUser = ref<User | null>(null);

// 是否显示编辑对话框
const showEditDialog = ref(false);

// 编辑表单
const editForm = ref({
  username: "",
  email: "",
  password: "",
});

// 表单验证错误
const formErrors = ref({
  username: "",
  email: "",
  password: "",
});

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true;
    const params: any = {
      skip: pagination.value.skip,
      limit: pagination.value.limit,
    };

    if (searchKeyword.value) {
      params.username = searchKeyword.value;
    }

    const response = await getUserList(params);
    users.value = response.users;
    total.value = response.total;
  } catch (error: any) {
    ElMessage.error("获取用户列表失败: " + (error || "网络错误"));
  } finally {
    loading.value = false;
  }
};

// 搜索用户
const handleSearch = () => {
  pagination.value.skip = 0;
  fetchUsers();
};

// 格式化时间
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false,
  });
};

// 过滤后的用户列表（显示格式化后的数据）
const displayUsers = computed(() => {
  return users.value.map((user) => ({
    ...user,
    registerTime: formatDate(user.created_at),
  }));
});

// 验证邮箱格式
const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 验证表单
const validateForm = (
  username: string,
  email: string,
  password?: string,
  isEdit: boolean = false
): boolean => {
  formErrors.value = { username: "", email: "", password: "" };
  let isValid = true;

  if (!username.trim()) {
    formErrors.value.username = "用户名不能为空";
    isValid = false;
  } else if (username.length < 3) {
    formErrors.value.username = "用户名至少3个字符";
    isValid = false;
  }

  if (!email.trim()) {
    formErrors.value.email = "邮箱不能为空";
    isValid = false;
  } else if (!validateEmail(email)) {
    formErrors.value.email = "邮箱格式不正确";
    isValid = false;
  }

  // 编辑时密码是可选的，新建时不需要密码
  if (!isEdit && password) {
    if (password.length < 6) {
      formErrors.value.password = "密码至少6个字符";
      isValid = false;
    }
  }

  return isValid;
};

// 打开编辑对话框
const openEditDialog = (user: User) => {
  editingUser.value = { ...user };
  editForm.value = {
    username: user.username,
    email: user.email,
    password: "",
  };
  formErrors.value = { username: "", email: "", password: "" };
  showEditDialog.value = true;
};

// 关闭编辑对话框
const closeEditDialog = () => {
  showEditDialog.value = false;
  editingUser.value = null;
  formErrors.value = { username: "", email: "", password: "" };
};

// 打开添加对话框
const openAddDialog = () => {
  ElMessage.error("添加用户功能暂未开放,请使用注册功能创建新用户");
};

// 保存编辑
const saveEdit = async () => {
  if (!editingUser.value) return;

  if (
    !validateForm(
      editForm.value.username,
      editForm.value.email,
      editForm.value.password,
      true
    )
  ) {
    return;
  }

  try {
    loading.value = true;
    const updateData: any = {
      username: editForm.value.username,
      email: editForm.value.email,
    };

    // 如果输入了新密码，则更新密码
    if (editForm.value.password) {
      updateData.password = editForm.value.password;
    }

    await updateUser(editingUser.value.id, updateData);
    ElMessage.success("用户信息更新成功");
    closeEditDialog();
    fetchUsers();
  } catch (error: any) {
    ElMessage.error("更新失败: " + (error || "网络错误"));
  } finally {
    loading.value = false;
  }
};

// 删除用户
const deleteUser = async (userId: number) => {
  ElMessageBox.confirm("确定要删除这个用户吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        loading.value = true;
        await deleteUserApi(userId);
        ElMessage.success("用户删除成功");
        fetchUsers();
      } catch (error: any) {
        ElMessage.error("删除失败: " + (error || "网络错误"));
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers();
});
</script>

<template>
  <div class="users-container">
    <div class="users-header">
      <h1>用户管理</h1>
      <div class="header-actions">
        <div class="search-box">
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索用户名或邮箱..."
            @keyup.enter="handleSearch"
          />
        </div>
        <button class="add-btn" @click="openAddDialog">
          <span class="icon">+</span>
          添加用户
        </button>
      </div>
    </div>

    <div class="users-content">
      <div class="table-container">
        <table class="users-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>用户名</th>
              <th>邮箱</th>
              <th>注册时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in displayUsers" :key="user.id">
              <td>{{ user.id }}</td>
              <td>
                <div class="username-cell">
                  {{ user.username }}
                </div>
              </td>
              <td>{{ user.email }}</td>
              <td>{{ user.registerTime }}</td>
              <td>
                <div class="action-buttons">
                  <button class="edit-btn" @click="openEditDialog(user)">
                    编辑
                  </button>
                  <button class="delete-btn" @click="deleteUser(user.id)">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>

        <div v-if="displayUsers.length === 0" class="empty-state">
          <p>没有找到用户</p>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <div v-if="showEditDialog" class="dialog-overlay" @click="closeEditDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h2>编辑用户</h2>
          <button class="close-btn" @click="closeEditDialog">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>用户名</label>
            <input
              v-model="editForm.username"
              type="text"
              placeholder="请输入用户名"
              :class="{ error: formErrors.username }"
            />
            <span v-if="formErrors.username" class="error-message">
              {{ formErrors.username }}
            </span>
          </div>
          <div class="form-group">
            <label>邮箱</label>
            <input
              v-model="editForm.email"
              type="email"
              placeholder="请输入邮箱"
              :class="{ error: formErrors.email }"
            />
            <span v-if="formErrors.email" class="error-message">
              {{ formErrors.email }}
            </span>
          </div>
          <div class="form-group">
            <label>新密码 (选填)</label>
            <input
              v-model="editForm.password"
              type="password"
              placeholder="留空则不修改密码"
              :class="{ error: formErrors.password }"
            />
            <span v-if="formErrors.password" class="error-message">
              {{ formErrors.password }}
            </span>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeEditDialog">取消</button>
          <button class="confirm-btn" @click="saveEdit">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.users-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: transparent;
  position: relative;
}

.users-header {
  padding: 24px 32px;
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.08) 0%,
    rgba(49, 190, 255, 0.03) 100%
  );
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(49, 190, 255, 0.2);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;

  h1 {
    font-size: 28px;
    font-weight: 600;
    color: #f6f9fe;
    font-family: "YouSheBiaoTiHei", sans-serif;
    text-shadow: 0 2px 8px rgba(49, 190, 255, 0.3);
  }
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-box {
  position: relative;

  input {
    width: 300px;
    padding: 10px 40px 10px 16px;
    background: rgba(26, 31, 58, 0.6);
    border: 1px solid rgba(49, 190, 255, 0.3);
    border-radius: 8px;
    font-size: 14px;
    color: #f6f9fe;
    font-family: "Alibaba PuHuiTi", sans-serif;
    transition: all 0.3s ease;

    &::placeholder {
      color: rgba(246, 249, 254, 0.5);
    }

    &:focus {
      border-color: rgba(49, 190, 255, 0.6);
      outline: none;
      background: rgba(26, 31, 58, 0.8);
      box-shadow: 0 0 0 3px rgba(49, 190, 255, 0.15),
        0 4px 12px rgba(49, 190, 255, 0.2);
    }
  }
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.25) 0%,
    rgba(49, 190, 255, 0.15) 100%
  );
  border: 1px solid rgba(49, 190, 255, 0.4);
  border-radius: 8px;
  color: #31beff;
  font-size: 14px;
  font-weight: 500;
  font-family: "Alibaba PuHuiTi", sans-serif;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(49, 190, 255, 0.2);

  .icon {
    font-size: 18px;
    font-weight: 300;
  }

  &:hover {
    background: linear-gradient(
      135deg,
      rgba(49, 190, 255, 0.35) 0%,
      rgba(49, 190, 255, 0.25) 100%
    );
    border-color: rgba(49, 190, 255, 0.6);
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(49, 190, 255, 0.3);
  }

  &:active {
    transform: translateY(0);
  }
}

.users-content {
  flex: 1;
  overflow: auto;
  padding: 24px 32px;
  position: relative;
}

.table-container {
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.05) 0%,
    rgba(49, 190, 255, 0.02) 100%
  );
  backdrop-filter: blur(20px);
  border: 1px solid rgba(49, 190, 255, 0.15);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

.users-table {
  width: 100%;
  border-collapse: collapse;

  thead {
    background: linear-gradient(
      135deg,
      rgba(49, 190, 255, 0.15) 0%,
      rgba(49, 190, 255, 0.08) 100%
    );

    th {
      padding: 16px 20px;
      text-align: left;
      font-size: 14px;
      font-weight: 600;
      color: rgba(49, 190, 255, 0.9);
      font-family: "Alibaba PuHuiTi", sans-serif;
      border-bottom: 1px solid rgba(49, 190, 255, 0.2);
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    }
  }

  tbody {
    tr {
      transition: all 0.3s ease;

      &:hover {
        background: rgba(49, 190, 255, 0.08);
        box-shadow: inset 0 0 20px rgba(49, 190, 255, 0.1);
      }

      td {
        padding: 16px 20px;
        font-size: 14px;
        color: rgba(246, 249, 254, 0.85);
        font-family: "Alibaba PuHuiTi", sans-serif;
        border-bottom: 1px solid rgba(49, 190, 255, 0.1);
      }
    }
  }
}

.username-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 8px;

  button {
    padding: 6px 16px;
    border: none;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    font-family: "Alibaba PuHuiTi", sans-serif;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .edit-btn {
    background: linear-gradient(
      135deg,
      rgba(49, 190, 255, 0.2) 0%,
      rgba(49, 190, 255, 0.1) 100%
    );
    border: 1px solid rgba(49, 190, 255, 0.3);
    color: #31beff;

    &:hover {
      background: linear-gradient(
        135deg,
        rgba(49, 190, 255, 0.3) 0%,
        rgba(49, 190, 255, 0.2) 100%
      );
      border-color: rgba(49, 190, 255, 0.5);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(49, 190, 255, 0.3);
    }
  }

  .delete-btn {
    background: linear-gradient(
      135deg,
      rgba(220, 38, 38, 0.2) 0%,
      rgba(220, 38, 38, 0.1) 100%
    );
    border: 1px solid rgba(220, 38, 38, 0.3);
    color: #ef4444;

    &:hover {
      background: linear-gradient(
        135deg,
        rgba(220, 38, 38, 0.3) 0%,
        rgba(220, 38, 38, 0.2) 100%
      );
      border-color: rgba(220, 38, 38, 0.5);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(220, 38, 38, 0.3);
    }
  }
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
  color: rgba(246, 249, 254, 0.5);

  p {
    font-size: 16px;
    font-family: "Alibaba PuHuiTi", sans-serif;
  }
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.dialog {
  background: linear-gradient(
    135deg,
    rgba(26, 31, 58, 0.95) 0%,
    rgba(10, 14, 39, 0.95) 100%
  );
  backdrop-filter: blur(20px);
  border: 1px solid rgba(49, 190, 255, 0.3);
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5), 0 0 20px rgba(49, 190, 255, 0.2);
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid rgba(49, 190, 255, 0.2);
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.08) 0%,
    rgba(49, 190, 255, 0.03) 100%
  );

  h2 {
    font-size: 20px;
    font-weight: 600;
    color: #f6f9fe;
    font-family: "YouSheBiaoTiHei", sans-serif;
    text-shadow: 0 2px 8px rgba(49, 190, 255, 0.3);
  }

  .close-btn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: transparent;
    border: 1px solid transparent;
    color: rgba(246, 249, 254, 0.6);
    font-size: 28px;
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(49, 190, 255, 0.1);
      border-color: rgba(49, 190, 255, 0.3);
      color: #31beff;
      transform: rotate(90deg);
    }
  }
}

.dialog-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }

  label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
    color: rgba(49, 190, 255, 0.9);
    font-family: "Alibaba PuHuiTi", sans-serif;
  }

  input {
    width: 100%;
    padding: 10px 16px;
    background: rgba(26, 31, 58, 0.6);
    border: 1px solid rgba(49, 190, 255, 0.3);
    border-radius: 8px;
    font-size: 14px;
    color: #f6f9fe;
    font-family: "Alibaba PuHuiTi", sans-serif;
    transition: all 0.3s ease;

    &::placeholder {
      color: rgba(246, 249, 254, 0.4);
    }

    &:focus {
      border-color: rgba(49, 190, 255, 0.6);
      outline: none;
      background: rgba(26, 31, 58, 0.8);
      box-shadow: 0 0 0 3px rgba(49, 190, 255, 0.15),
        0 4px 12px rgba(49, 190, 255, 0.2);
    }

    &.error {
      border-color: rgba(220, 38, 38, 0.6);

      &:focus {
        box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.15),
          0 4px 12px rgba(220, 38, 38, 0.2);
      }
    }
  }

  .error-message {
    display: block;
    margin-top: 6px;
    font-size: 13px;
    color: #ef4444;
    font-family: "Alibaba PuHuiTi", sans-serif;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid rgba(49, 190, 255, 0.2);
  background: linear-gradient(
    135deg,
    rgba(49, 190, 255, 0.03) 0%,
    rgba(49, 190, 255, 0.01) 100%
  );

  button {
    padding: 10px 24px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    font-family: "Alibaba PuHuiTi", sans-serif;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .cancel-btn {
    background: rgba(49, 190, 255, 0.08);
    border: 1px solid rgba(49, 190, 255, 0.2);
    color: rgba(246, 249, 254, 0.7);

    &:hover {
      background: rgba(49, 190, 255, 0.15);
      border-color: rgba(49, 190, 255, 0.3);
      color: #f6f9fe;
      transform: translateY(-2px);
    }
  }

  .confirm-btn {
    background: linear-gradient(
      135deg,
      rgba(49, 190, 255, 0.3) 0%,
      rgba(49, 190, 255, 0.2) 100%
    );
    border: 1px solid rgba(49, 190, 255, 0.4);
    color: #31beff;
    box-shadow: 0 2px 8px rgba(49, 190, 255, 0.2);

    &:hover {
      background: linear-gradient(
        135deg,
        rgba(49, 190, 255, 0.4) 0%,
        rgba(49, 190, 255, 0.3) 100%
      );
      border-color: rgba(49, 190, 255, 0.6);
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(49, 190, 255, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }
}
</style>
